// return [<div/>, <div id='a'/>, <div class='b'/>] 
export const getComposedPathEle = (e) => { 
  if (!e) return [];
  //如果支持path属性，直接返回path属性
  //如果不支持，就通过composedPath方法获取
  let pathArr = e.path || (e.composedPath && e.composedPath());
  if ((pathArr || []).length) { 
    return pathArr;
  }

  return getPathArr(e.target);
}
// 既不支持 .path
// 也不支持 .composedPath()
// 就通过dom节点依次向上找
/// target: dom节点
// return [<div/>, <div id='a'/>, <div class='b'/>] 
function getPathArr(target) {
  const nodes = []

  while (target && target.parentNode) {
    nodes.push(target)
    target = target.parentNode
  }

  return [...nodes, document, window]
}
/**
 * [<div/>, <div id='a'/>, <div class='b'/>] --> ['div', 'div#a', 'div.b']
 */
export const getComposedPath = (e) => { 
  if (!e) return [];
  const composedPathEle = getComposedPathEle(e);

  const composedPath = composedPathEle.reverse().slice(2).map(ele => { 
    let selector = ele.tagName.toLowerCase();
    if (ele.id) { 
      selector += `#${ele.id}`;
    }
    if (ele.className) { 
      selector += `.${ele.className}`;
    }
    return selector;
  });

  return composedPath;
}
/**
 * e: event
 * ['div', 'div#a', 'div.b'] --> 'div > div#a > div.b'
 */
export const getPaths = (e) => { 
  if (!e) return '';
  const composedPath = getComposedPath (e);
  const selectors = composedPath.join(' > ');
  return selectors;
}
